﻿using Repository.MODELs;
using Repository.ServiceConnection.Controllers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Repository.Repositories
{
    public class TaskLogRepository
    {
        private Dictionary<int, ObservableCollection<TaskLogModel>> _logs = new Dictionary<int,ObservableCollection<TaskLogModel>>();

        private readonly SemaphoreSlim _sl = new SemaphoreSlim(1);

        public async Task<ObservableCollection<TaskLogModel>> GetLogForTask(int taskid)
        {
            await _sl.WaitAsync();

            try
            {
                if (_logs != null && _logs.ContainsKey(taskid))
                {
                    return _logs[taskid];
                }

                _logs[taskid] = await TaskLogController.Instance.GetTaskLogsAsync(taskid);

                return _logs[taskid];
            }
            finally
            {
                _sl.Release();
            }
        }

        public void Clearcache()
        {
            _logs = new Dictionary<int,ObservableCollection<TaskLogModel>>();
        }

        #region Singleton
        private TaskLogRepository()
        {

        }

        public static TaskLogRepository Instance
        {
            get { return Nested._instance; }
        }

        private class Nested
        {
            /// <summary>
            /// Instance of Repository for Singleton pattern.
            /// </summary>
            internal static readonly TaskLogRepository _instance = new TaskLogRepository();

            /// <summary>
            /// Explicit static constructor to tell C# compiler not to mark type as beforefieldinit.
            /// </summary>
            static Nested()
            {
            }
        }
        #endregion
    }
}
